package org.ats.mail;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Service("MailTemplateProcessor")
public class MailTemplateProcessor implements MailTemplateProcessing {
	
	@Autowired
	private VelocityEngine velocityEngine;
	
	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public Properties propertyLoader(MailTemplates mailTemp){
		Properties allProps = new Properties();
		Properties templateProps = new Properties();
		String tempName = mailTemp.name() + "." ;

		try(InputStream is = getClass().getResourceAsStream("/templates/templates.properties")) {
			allProps.load(is);
			for(Object prop : allProps.keySet()){
				if( prop.toString().contains(tempName) || prop.toString().contains("GENERIC.") ){
					templateProps.put(prop.toString().substring(prop.toString().lastIndexOf(".") + 1), allProps.get(prop));
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return templateProps;
	}
	
	public MailContent ProcessTemplate(MailTemplates mailTemp){
		
		Properties templateProps = propertyLoader(mailTemp);
		MailContent mc = new MailContent();
		Map<String, Object> model = new HashMap<String, Object>();
		
		model.put("userName", templateProps.getProperty("userName").toString());
		
		mc.setMailTemp(mailTemp);
		mc.setSubject(templateProps.getProperty("subject"));
		mc.setFrom(templateProps.getProperty("from"));
		mc.setInlinePhotoName(templateProps.getProperty("inline_photo_name"));
		//System.out.println(templateProps.getProperty("inline_photo_path"));
		mc.setInlinePhotoFile(new File(templateProps.getProperty("inline_photo_path")));
		mc.setMailText(VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), mailTemp.toString(), "UTF-8",model));
		
		return mc;
	}
}
